import React, { useState, useEffect } from "react"
import PubSub from "pubsub-js"
import Header from "./components/Header/Header"
import List from "./components/List/List"
import Footer from "./components/Footer/Footer"
import Item from "./components/Item/Item"
import "./App.css"
export default function App() {
  const [list, setList] = useState([
    { id: 1, todoName: "吃饭", isDone: true },
    { id: 2, todoName: "睡觉", isDone: false },
  ])

  console.log("app里面", list)

  useEffect(() => {
    //添加任务
    const addId = PubSub.subscribe("add", (topic, todoName) => {
      const todo = {
        id: Date.now(),
        todoName,
        isDone: false,
      }
      setList((list) => {
        const newList = [...list]
        newList.push(todo)
        return newList
      })
    })

    const updateId = PubSub.subscribe("update", (topic, id) => {
      setList((list) => {
        const newList = [...list]
        newList.forEach((item) => {
          if (item.id === id) item.isDone = !item.isDone
        })
        return newList
      })
    })
    return () => {
      PubSub.unsubscribe(addId)
      PubSub.unsubscribe(updateId)
    }
  }, [])

  return (
    <div className="todo-container">
      <div className="todo-wrap">
        <Header></Header>
        <div>
          <List>
            {list.map((item) => {
              return <Item key={item.id} todo={item}></Item>
            })}
          </List>
          <Footer></Footer>
        </div>
      </div>
    </div>
  )
}
